//
//  DZDiningRoomSearchViewController.m
//  DaZhePrivateHomeCuisineClient
//
//  Created by zouzhisheng on 14-12-9.
//  Copyright (c) 2014年 zouzhisheng. All rights reserved.
//

#import "DZDiningRoomSearchViewController.h"
#import "DZRestautantModel.h"
#import "DZAdviceTableViewCell.h"
#import "DZWebViewController.h"
@implementation DZDiningRoomSearchNav
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor clearColor];
    DZDiningRoomSearchViewController *classVC=[[DZDiningRoomSearchViewController alloc] init];
    self.viewControllers = @[classVC];
    
}

@end


@interface DZDiningRoomSearchViewController (){
    NSArray *titleArray;
    NSArray *array1;
    NSArray *array2;
    NSArray *array3;
    NSArray *array4;
    NSMutableArray *dataArray;
    NSMutableDictionary *queryDir;
    int pageNum;
    BOOL downPull;
}

@end

@implementation DZDiningRoomSearchViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [SharedAppDelegate.home.tabBarController setTabBarHidden:NO];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBarHidden=YES;
    dataArray=[NSMutableArray array];
    pageNum=1;
    titleArray=[NSArray arrayWithObjects:@"菜品",@"特色菜",@"档次",@"区域", nil];
    array1=@[@"水煮鱼",@"骨头",@"鱼头"];
    array2=@[@"水煮鱼",@"骨头",@"鱼头",@"水煮鱼",@"骨头"];
    array3=@[@"水煮鱼",@"骨头",@"鱼头",@"水煮鱼",@"骨头",@"水煮鱼",@"骨头"];
    array4=@[@"水煮鱼",@"骨头",@"鱼头",@"水煮鱼",@"骨头",@"水煮鱼",@"骨头",@"水煮鱼",@"骨头"];
    queryDir=[[NSMutableDictionary alloc] initWithCapacity:0];
    [queryDir setObject:@"group" forKey:@"act"];
    [self navView];
    [self addTitle:@"餐厅查询"];
    [self loadSubView];
    [self loadData];
    // Do any additional setup after loading the view.
}
-(void)loadSubView
{
    [self.view addSubview:self.menuView];
    [self.view addSubview:self.diningRoomListView];
    __block typeof(self)weakSelf = self;
    [self.diningRoomListView addPullToRefreshWithActionHandler:^{
        weakSelf->downPull=NO;
        weakSelf->pageNum=1;
        NSString *caipin=weakSelf->queryDir[@"caipin"];
        NSString *tesecai=weakSelf->queryDir[@"tesecai"];
        NSString *dangci=weakSelf->queryDir[@"dangci"];
        NSString *area=weakSelf->queryDir[@"area"];
        if ((!caipin||caipin.length==0)&&(!tesecai||tesecai.length==0)&&(!dangci||dangci.length==0)&&(!area||area.length==0) ) {
             [weakSelf loadData];
        }else{
            [weakSelf combinationQuery:weakSelf->queryDir];
        }
        [weakSelf.diningRoomListView.infiniteScrollingView setEnabled:YES];
    }];
    [self.diningRoomListView addInfiniteScrollingWithActionHandler:^{
        weakSelf->downPull=YES;
        weakSelf->pageNum++;
        NSString *caipin=weakSelf->queryDir[@"caipin"];
        NSString *tesecai=weakSelf->queryDir[@"tesecai"];
        NSString *dangci=weakSelf->queryDir[@"dangci"];
        NSString *area=weakSelf->queryDir[@"area"];
        if ((!caipin||caipin.length==0)&&(!tesecai||tesecai.length==0)&&(!dangci||dangci.length==0)&&(!area||area.length==0) ) {
            [weakSelf loadData];
        }else{
            [weakSelf combinationQuery:weakSelf->queryDir];
        }
    }];

}
-(void)stopLoad:(int)totalPages{
    if(self.diningRoomListView.pullToRefreshView.state == SVPullToRefreshStateLoading)
        [self.diningRoomListView.pullToRefreshView stopAnimating];
    if(self.diningRoomListView.infiniteScrollingView.state == SVInfiniteScrollingStateLoading)
        [self.diningRoomListView.infiniteScrollingView stopAnimating];
    if(pageNum < totalPages){
        [self.diningRoomListView.infiniteScrollingView setEnabled:YES];
    }
    if (pageNum == totalPages) {
        [self.diningRoomListView.infiniteScrollingView setEnabled:NO];
        [self.diningRoomListView.infiniteScrollingView hasDataEnd];
    }
    
}

#pragma mark-获取地区信息
-(void)loadDataArea{
    if (areaModel && areaModel.area.count>0) {
         [self reshMenuData:areaModel.area];
    }else{
        NSDictionary *dir=[NSDictionary dictionaryWithObjectsAndKeys:@"area",@"act", nil];
        [[BaseService shareNetworkService] requestActivityParameters:dir DataSouce:nil RequestType:Request_GetCategoryInfoArea Block:^(__weak id data, NSError *error) {
            if (!error) {
                areaModel=data;
                [self reshMenuData:areaModel.area];
            }
            
        }];
 
    }
}
#pragma mark-获取其他的信息
-(void)loadOtherInfo:(int)type{
     NSDictionary *dir=[NSDictionary dictionaryWithObjectsAndKeys:@"other",@"act",[NSString stringWithFormat:@"%d",type],@"type", nil];
    switch (type) {
        case 3:
        { //档次
            if (dangciModel &&dangciModel.dangci.count>0) {
                 [self reshMenuData:dangciModel.dangci];
            }else{
                [[BaseService shareNetworkService] requestActivityParameters:dir DataSouce:nil RequestType:Request_GetCategoryInfoDangci Block:^(__weak id data, NSError *error) {
                    if (!error) {
                        dangciModel=data;
                        [self reshMenuData:dangciModel.dangci];
                    }
                    
                }];
 
            }
        }
            break;
        case 6:
        { //特色菜
            if (tesecaiModel &&tesecaiModel.tesecai.count>0) {
                 [self reshMenuData:tesecaiModel.tesecai];
            }else{
                [[BaseService shareNetworkService] requestActivityParameters:dir DataSouce:nil RequestType:Request_GetCategoryInfoTesecai Block:^(__weak id data, NSError *error) {
                    if (!error) {
                        tesecaiModel=data;
                        [self reshMenuData:tesecaiModel.tesecai];
                    }
                }];
 
            }
            
        }
            break;
        case 7:
        { //菜品
            if (caipinModel&&caipinModel.caipin.count>0) {
                 [self reshMenuData:caipinModel.caipin];
            }else{
                [[BaseService shareNetworkService] requestActivityParameters:dir DataSouce:nil RequestType:Request_GetCategoryInfoCaiPin Block:^(__weak id data, NSError *error) {
                    if (!error) {
                        caipinModel=data;
                        [self reshMenuData:caipinModel.caipin];
                    }
                    
                }];
 
            }
        }
            break;
        
            
        default:
            break;
    }
    
    
}
-(void)loadData{
    NSDictionary *dic=[NSDictionary dictionaryWithObjectsAndKeys:@"2",@"area",@"group",@"act",[NSNumber numberWithInt:pageNum],@"page",@"10",@"count", nil];
    [[BaseService shareNetworkService] requestActivityParameters:dic DataSouce:self RequestType:Request_RestanutantCommonQuery Block:^(__weak id data, NSError *error) {
        if (!error) {
            if (!downPull) {
              [dataArray removeAllObjects];
            }
            if (pageNum==1) {
                DZAdviceInfoSubModel *adviceInfoSubModel=SharedAppDelegate.home.adviceInfoModel.adviceInfo[0];
                [dataArray addObject:adviceInfoSubModel];
            }
            DZRestautantModel *model=data;
            if (model.subjectInfo.count>0) {
                for (int i=0; i<model.subjectInfo.count; i++) {
                    [dataArray addObject:model.subjectInfo[i]];
                }
            }
            if (dataArray.count<=1) {
                self.diningRoomListView.hidden=YES;
                self.tempLabel.top=self.menuView.bottom;
                self.tempLabel.height=SYSTEM_VERSION>=7.0?SCREEN_HEIGHT-self.navView.height-self.menuView.height-49:SCREEN_HEIGHT-self.navView.height-self.menuView.height-20-49;
                self.tempLabel.hidden=NO;
                return ;
            }
            if (dataArray.count>1) {
                self.diningRoomListView.hidden=NO;
                self.tempLabel.hidden=YES;
            }
            [self.diningRoomListView reloadData];
            [self stopLoad:[model.pageCount intValue]];
        }
        
    }];
}
#pragma mark-组合查询
-(void)combinationQuery:(NSDictionary *)paramDir{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc] init];
    NSLog(@"组合查询传入的参数====%@",paramDir);
    if (paramDir) {
        [dic addEntriesFromDictionary:paramDir];
    }
    [dic setObject:[NSNumber numberWithInt:pageNum] forKey:@"page"];
    [dic setObject:@"10" forKey:@"count"];
    [[BaseService shareNetworkService] requestActivityParameters:dic DataSouce:self RequestType:Request_RestanutantCommonQuery Block:^(__weak id data, NSError *error) {
        if (!error) {
            if (!downPull) {
                [dataArray removeAllObjects];
            }
            if (pageNum==1) {
                DZAdviceInfoSubModel *adviceInfoSubModel=SharedAppDelegate.home.adviceInfoModel.adviceInfo[0];
                [dataArray addObject:adviceInfoSubModel];
            }
            DZRestautantModel *model=data;
            if (model.subjectInfo.count>0) {
                for (int i=0; i<model.subjectInfo.count; i++) {
                    [dataArray addObject:model.subjectInfo[i]];
                }
            }
            if (dataArray.count<=1) {
                self.diningRoomListView.hidden=YES;
                self.tempLabel.top=self.menuView.bottom;
                self.tempLabel.height=SYSTEM_VERSION>=7.0?SCREEN_HEIGHT-self.navView.height-self.menuView.height-49:SCREEN_HEIGHT-self.navView.height-self.menuView.height-20-49;
                self.tempLabel.hidden=NO;
                return ;
            }
            if (dataArray.count>1) {
                self.diningRoomListView.hidden=NO;
                self.tempLabel.hidden=YES;
            }

            [self.diningRoomListView reloadData];
            [self stopLoad:[model.pageCount intValue]];
        }
    }];
}
-(void)reshMenuData:(NSArray *)array{
    [_menuView.menuArray removeAllObjects];
    _menuView.menuArray=[NSMutableArray arrayWithArray:array];
    id obj=array[0];
    if ([obj isKindOfClass:[DZAreaSubModel class]]) {
        for(DZAreaSubModel *subModel in _menuView.menuArray){
            if ([subModel.aid intValue]==1) {
                [_menuView.menuArray removeObject:subModel];
                break;
            }
        }
 
    }
    [_menuView.menuArray insertObject:@"全部" atIndex:0];
    [_menuView.menuListView reloadData];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)backAction:(UIButton*)bt
{
    [SharedAppDelegate.home.tabBarController.navigationController popViewControllerAnimated:YES];
}
#pragma mark-getter
-(CustomMenuView*)menuView
{
    if (!_menuView) {
        _menuView=[[CustomMenuView alloc] initWithFrame:CGRectMake(0,self.navView.bottom, SCREEN_WIDTH, 40) WithTitleArray:titleArray];
        _menuView.delegate=self;
    }
    return _menuView;
}
-(UITableView*)diningRoomListView
{
    if (!_diningRoomListView) {
        _diningRoomListView=[[UITableView alloc] initWithFrame:CGRectMake(0,self.menuView.bottom,SCREEN_WIDTH,SYSTEM_VERSION>=7.0?SCREEN_HEIGHT-self.navView.height-self.menuView.height-49:SCREEN_HEIGHT-self.navView.height-self.menuView.height-20-49) style:UITableViewStylePlain];
        _diningRoomListView.delegate=self;
        _diningRoomListView.dataSource=self;
        [self.view addSubview:_diningRoomListView];
    }
    return _diningRoomListView;
}
#pragma mark-CustomMenuViewDelegate
-(void)tapType:(int)type{
    switch (type) {
        case 100:
            //菜品
            [self loadOtherInfo:7];
            break;
        case 101:
           //特色菜
            [self loadOtherInfo:6];
            break;
        case 102:
            //档次
            [self loadOtherInfo:3];
            break;
        case 103:
            //区域
            [self loadDataArea];
            break;
            
        default:
            break;
    }
}
-(void)selectDir:(NSDictionary *)dir{
    pageNum=1;
    [dataArray removeAllObjects];
    if (dir[@"caipin"]) {
        [queryDir setObject:dir[@"caipin"] forKey:@"caipin"];
        [queryDir removeObjectForKey:@"tesecai"];
        [queryDir removeObjectForKey:@"dangci"];
        UIButton *bt1=_menuView.btArray[1];
        UIButton *bt2=_menuView.btArray[2];
        [bt1 setTitle:@"特色菜" forState:UIControlStateNormal];
        [bt2 setTitle:@"档次" forState:UIControlStateNormal];
         
    }
    if (dir[@"tesecai"]) {
        [queryDir setObject:dir[@"tesecai"] forKey:@"tesecai"];
        [queryDir removeObjectForKey:@"caipin"];
        [queryDir removeObjectForKey:@"dangci"];
        UIButton *bt1=_menuView.btArray[0];
        UIButton *bt2=_menuView.btArray[2];
        [bt1 setTitle:@"菜品" forState:UIControlStateNormal];
        [bt2 setTitle:@"档次" forState:UIControlStateNormal];

    }
    if (dir[@"dangci"]) {
        [queryDir setObject:dir[@"dangci"] forKey:@"dangci"];
        [queryDir removeObjectForKey:@"tesecai"];
        [queryDir removeObjectForKey:@"caipin"];
        UIButton *bt1=_menuView.btArray[0];
        UIButton *bt2=_menuView.btArray[1];
        [bt1 setTitle:@"菜品" forState:UIControlStateNormal];
        [bt2 setTitle:@"特色菜" forState:UIControlStateNormal];
    }
    if (dir[@"area"]) {
        [queryDir setObject:dir[@"area"] forKey:@"area"];
    }
    [self combinationQuery:queryDir];
}
#pragma mark - table datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id obj=dataArray[indexPath.row];
    if ([obj isKindOfClass:[DZAdviceInfoSubModel class]]) {
        DZAdviceInfoSubModel *model=obj;
        static NSString *cellIdentifier=@"DZAdviceTableViewCell";
        DZAdviceTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DZAdviceTableViewCell"  owner:self options:nil] lastObject];
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        [cell loadImageUrlStr:model.pic];
        return cell;
    }
    if ([obj isKindOfClass:[DZSubRestautantModel class]]) {
        static NSString *identifier = @"DZDinningRoomTableViewCell";
        DZDinningRoomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"DZDinningRoomTableViewCell"  owner:self options:nil] lastObject];
        }
        cell.selectionStyle=UITableViewCellSelectionStyleNone;
        [cell loadData:obj];
        return cell;
  
    }
    return nil;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    id obj=dataArray[indexPath.row];
    if ([obj isKindOfClass:[DZAdviceInfoSubModel class]]){
//        DZAdviceInfoSubModel *model=obj;
//        CGSize size=[Common downloadImageSizeWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",API_DOMAIN,model.pic]]];
//        float imageH=size.height*SCREEN_WIDTH/size.width;
        return 49;

    }
    if ([obj isKindOfClass:[DZSubRestautantModel class]]){
        return 90;
    }
    return 0;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     id obj=dataArray[indexPath.row];
    if ([obj isKindOfClass:[DZSubRestautantModel class]]) {
        DZSubRestautantModel *model=obj;
        DZDinningDetailViewController *dinningDetail=[[DZDinningDetailViewController alloc] init];
        dinningDetail.sid=model.sid;
        [self.navigationController pushViewController:dinningDetail animated:YES];
    }
    if ([obj isKindOfClass:[DZAdviceInfoSubModel class]]) {
        DZAdviceInfoSubModel *model=obj;
        DZWebViewController *webVC=[[DZWebViewController alloc] init];
        webVC.adviceInfoSubModel=model;
        [self.navigationController pushViewController:webVC animated:YES];
    }

  
}
- (UIView *)viewForLoadAnimationAtService:(RequestType)type{
    return self.view;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
